package web.admin.shop;


import domain.shop.DeliveryMethod;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import service.facade.admin.ShopAdminService;
import web.admin.components.TinyMceBehavior;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Provides settings of particular delivery method
 */
public final class DeliveryMethodPanel extends Panel {

    @SpringBean
    private ShopAdminService shopAdminService;
    private final IModel<DeliveryMethod> deliveryMethodModel;
    private static Logger logger = Logger.getLogger(DeliveryMethodPanel.class.getName());

    public DeliveryMethodPanel(String id, final Long pageId, final DeliveryMethodAdminPanel parent) {
        super(id);
        deliveryMethodModel = new LoadableDetachableModel<DeliveryMethod>() {

            @Override
            protected DeliveryMethod load() {
                return shopAdminService.findDeliveryMethodById(pageId);
            }
        };
        add(new Form<DeliveryMethod>("form", deliveryMethodModel) {

            {
                add(new TextField("name", new PropertyModel(deliveryMethodModel, "name")).setRequired(true));
                add(new TextField("price", new PropertyModel(deliveryMethodModel, "price")));
                final TextArea textArea = new TextArea("methodDescription", new PropertyModel(deliveryMethodModel, "methodDescription"));
                textArea.add(new TinyMceBehavior(true));
                add(textArea);

            }

            @Override
            protected void onSubmit() {
                try {
                    shopAdminService.updateDeliveryMethod(deliveryMethodModel.getObject());

                    info(getLocalizer().getString("saved", this));
                } catch (Exception e) {
                    logger.log(Level.SEVERE, null, e);
                    error(getLocalizer().getString("system.error", this));
                }
            }
        });

        add(new Form("actions") {

            {
                add(new Link("delete") {

                    @Override
                    public void onClick() {
                        shopAdminService.deleteDeliveryMethod(deliveryMethodModel.getObject());
                        parent.replacePanelToEmpty();
                    }
                });
            }
        });
    }


}
